<?php

namespace backend\controllers;

use Yii;
use common\models\Order;
use common\models\OrderSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\OrderProduct;
use common\models\Product;
/**
 * OrderController implements the CRUD actions for Order model.
 */
class OrderController extends AController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
    *导出Execl表格
    *@param $expFileName  string  导出文件名称
    *@param $expTitle  string  表格中页签的名称
    *@param $expCellName  array  列名
    *@param $expTableData  array  表格数据
    */
    public function actionExport(){

        $db = Yii::$app->db;

        $get = Yii::$app->request->get();

        if(!$get){
            exit('Wrong time format');
        }

        if(isset($get['start_time'])){
            $start_time = $get['start_time'].' 00:00:00';
            $where = " >= '$start_time'";
        }

        if(isset($get['end_time'])){
            $end_time = $get['end_time'].' 23:59:59';
            $where = " <= '$end_time'";
        }

        if(isset($get['start_time']) && isset($get['end_time'])){
            $where = " >= '$start_time' AND `create_time` <= '$end_time'";
        }
        
        $sql = "SELECT * FROM `order` WHERE `create_time`".$where;
        $query_res = Yii::$app->db->createCommand($sql)->queryAll();

        if(!$query_res){
            exit('without record');
        }

        $expFileName = date('Ymd').'订单记录';
        $label = (new Order)->attributeLabels();

        $expCellName = [];
        foreach ($label as $k => $v) {
            $list[0] = $k;
            $list[1] = $v;
            array_push($expCellName, $list);
        }
        foreach ($query_res as $k => $v) {
            $query_res[$k]['user_id'] = \common\models\User::findOne($v['user_id'])->username;
            $query_res[$k]['order_status'] = Order::itemAlias('order_status',$v['order_status']);
            $query_res[$k]['shipping_status'] = Order::itemAlias('shipping_status',$v['shipping_status']);
            $query_res[$k]['pay_status'] = Order::itemAlias('pay_status',$v['pay_status']);
            $query_res[$k]['address_id'] = \common\models\Address::findOne($v['address_id'])->address_detail;
        }

        $expTableData = $query_res;

        $do=exportExcel("订单记录".date('Ymd'),$expFileName,$expCellName,$expTableData);
    }

    /**
     * Lists all Order models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Order model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $list = OrderProduct::find()
                ->where(['order_id'=>$id])
                ->asarray()
                ->all();
        foreach ($list as $key => $value) {

            $list[$key]['product']=Product::find()
                ->select('name,img_url,id')
                ->where(['id'=>$value['product_id']])
                ->asarray()
                ->all();
        }
                                           
        return $this->render('view', [
            'model' => $this->findModel($id),
            'list' => $list,
        ]);
    }

    public function actionGetlist(){
        $uid = Yii::$app->request->post('uid');
        $list = Order::address_list($uid);
        return json_encode($list);
    }

    /**
     * Creates a new Order model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Order();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Order model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Order model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Order model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Order the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Order::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
